#!/bin/bash
#
# Updates subscription and runs agents
#
# Author:   Dr. Mike Murphy (mmurphy2@coastal.edu)
# Revision: 18 November 2013
#
#   Copyright 2012-2013 Coastal Carolina University
#
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.
#


## p_cmd_update_help
##
## Echoes help information for the update command. Returns 0.
##
function p_cmd_update_help() {
	cat << EOF
Usage: pulley update [--no-agents | --cron]

Runs Pulley to complete system administration tasks. Updates the local
subscription if necessary, then runs all agents. Update runs are locked,
so that only one update operation may occur at any time.

If the --no-agents argument is given, only the subscription and context
data are updated. System administration agents will not be executed in
this case.

Alternatively, the --cron option may be given, which will run agents only
if the pulley/enable_cron context item is set to "true" (all lower-case
string value). The --no-agents option overrides the --cron option, if both
are specified.
EOF
	return 0
}


## p_cmd_update_summary
##
## Echoes summary information for the update command. Returns 0.
##
function p_cmd_update_summary() {
	echo "Updates subscription and runs agents"
	return 0
}


## p_cmd_update [--no-agents | --cron]
##
## Implements the Pulley update command. Updates the Pulley subscription if
## needed, then runs agents unless --no-agents is given as an option. If
## --cron is specified, retrieves the pulley/enable_cron context item. If
## this context item is set to any value other than "true", this command
## will update the Pulley subscription but not run agents.
##
## Returns 0 upon success, non-zero if an error occurs.
##
function p_cmd_update() {
	local status=0
	local no_agents=0
	
	for arg in "$@"; do
		case "${arg}" in
			"--cron")
				local cron_setting=$(get_context pulley/enable_cron)
				[ "${cron_setting}" != "true" ] && no_agents=1
			;;
			"--no-agents")
				no_agents=1
			;;
			*)
				echo "Invalid option: ${arg}"
				status=2
			;;
		esac
	done
	
	if [[ ${status} -eq 0 ]]; then
		psub_update_subscription
		import_subscription
		if [[ ${no_agents} -eq 0 ]]; then
			run_agents
			status=$?
		fi
	fi
	
	return ${status}
}
